package com.example.administrator.testsdk;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.verifysdk.AuthUtil;
import com.example.verifysdk.SpHelper;
import com.example.verifysdk.auth.GoogleAuthenticator;
import com.example.verifysdk.auth.GoogleAuthenticatorConfig;
import com.example.verifysdk.compare.CompareActivity;
import com.example.verifysdk.compare.RegisterObjBean;
import com.example.verifysdk.creatcode.CreatCodeActivity;
import com.example.verifysdk.scancode.ShowQRInfoActivity;
import com.example.verifysdk.scancode.google.zxing.integration.android.IntentIntegrator;
import com.example.verifysdk.scancode.google.zxing.integration.android.IntentResult;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.concurrent.TimeUnit;

import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    EditText firstEt;
    EditText secondEt;
    EditText totpEt;
    TextView firstTv;

    private GoogleAuthenticatorConfig.GoogleAuthenticatorConfigBuilder gAcb = new GoogleAuthenticatorConfig.GoogleAuthenticatorConfigBuilder().setTimeStepSizeInMillis(TimeUnit.SECONDS.toMillis(60)).setWindowSize(3).setCodeDigits(6);
    private GoogleAuthenticator gAuth = new GoogleAuthenticator(gAcb.build());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
    }

    private void initView() {
        firstEt = (EditText) findViewById(R.id.first_et);
        secondEt = (EditText) findViewById(R.id.second_et);
        totpEt = (EditText) findViewById(R.id.totp_et);
        firstTv = (TextView) findViewById(R.id.first_tv);

        firstEt.setText("1000");
//        secondEt.setText("b7149e70-7017-11e7-9005-3f5f960065f4");
        secondEt.setText("df1f2940-7a6f-11e8-a66e-bdbe3bb072a9");
        secondEt.setText("8427cde0-7b63-11e8-86aa-ff6faa843823");
        secondEt.setText("9b9d6b50-7d9e-11e8-a5f1-3d7869c35022");
        secondEt.setText("e0790660-7f71-11e8-8716-c5777e61af7c");
        secondEt.setText("a76ed430-8354-11e8-9983-93a3eb51fce1");
    }

    private void initData() {
//        Provider[] providers = Security.getProviders();
//        for (Provider provider : providers) {
//            Log.i("CRYPTO", "provider: " + provider.getName());
//            Set<Provider.Service> services = provider.getServices();
//            for (Provider.Service service : services) {
//                Log.i("CRYPTO", "  algorithm: " + service.getAlgorithm());
//            }
//        }
    }

    //人脸比对功能
    public void but1(View view) {
        Intent intent = new Intent(this, CompareActivity.class);
        Bundle bundle = new Bundle();
//        bundle.putString("totp", totpEt.getText().toString().trim());
        bundle.putString("partnerId", firstEt.getText().toString().trim());
        bundle.putString("userId", secondEt.getText().toString().trim());
        bundle.putString("phone", "");
        intent.putExtras(bundle);
        startActivityForResult(intent, 666);
//        CreatCodeActivity.startCode();
//        CompareActivity.st();
//        finish();
    }

    //扫码识别
    public void but2(View view) {
        Intent intent = new Intent(this, CreatCodeActivity.class);
        Bundle bundle = new Bundle();
//        bundle.putString("totp", totpEt.getText().toString().trim());
//        bundle.putString("partnerId", firstEt.getText().toString().trim());
//        bundle.putString("userId", secondEt.getText().toString().trim());
        bundle.putString("partnerId", firstEt.getText().toString().trim());
        bundle.putString("userId", secondEt.getText().toString().trim());
        intent.putExtras(bundle);
        startActivity(intent);

        Log.i(TAG, "---mAppPartner===" + bundle.get("partnerId"));
        Log.i(TAG, "---mAppPartnerRemark===" + bundle.get("userId"));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if(result != null) {
            if(result.getContents() == null) {
                Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
        Log.i(TAG, "---requestCode===" + requestCode);
        Log.i(TAG, "---resultCode===" + resultCode);
//        Log.i(TAG, "---id===" + data.getStringExtra("identity"));
    }

    public void but3(View view) {

        Intent intent = new Intent(this, ShowQRInfoActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("partnerId", firstEt.getText().toString().trim());
        bundle.putString("userId", secondEt.getText().toString().trim());
        intent.putExtras(bundle);
        startActivityForResult(intent, 777);
    }

    private void scanCode(){
        IntentIntegrator intentIntegrator = new IntentIntegrator(this);
        intentIntegrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
        intentIntegrator.initiateScan();
    }
//    private static SecretKey deriveKeyInsecurely(String password, int
//            keySizeInBytes) {
//        byte[] passwordBytes = password.getBytes(StandardCharsets.US_ASCII);
//        return new SecretKeySpec(
//                InsecureSHA1PRNGKeyDerivator.deriveInsecureKey(
//                        passwordBytes, keySizeInBytes),
//                "AES");
//    }

    public void but4(View view) {
        SpHelper spHelper = new SpHelper(this);
        spHelper.putPartenrRemark(secondEt.getText().toString().trim());
        RegisterObjBean bean = new RegisterObjBean();
        bean.setSecret("");
        bean.setToken("");
        spHelper.putRegistInfo(bean);
        spHelper.putString(SpHelper.SDK_FACE_PH, "");
    }

    public void but5(View view) {
        SpHelper spHelper = new SpHelper(this);
        spHelper.putPartenrRemark(secondEt.getText().toString().trim());
        StringBuffer info = new StringBuffer();
        info.append("imgUrl=" + spHelper.getSdkFacePh() + "\n");
        info.append("secret=" + spHelper.getSdkSecret() + "\n");
        info.append("token=" + spHelper.getSdkToken() + "\n");
        info.append("userId=" + spHelper.getSdkUserId() + "\n");
        firstTv.setText(info.toString());
    }

    public void but6(View view) {
        String sec = "62BDYFYDTYHL4CP7";
        int totp = AuthUtil.getTotp(sec);
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("secret=" + sec + "\n");
        stringBuffer.append("totp=" + totp);
        firstTv.setText(stringBuffer.toString());
    }

    private void test1(){
           /* User types in their password: */
        String password = "password";

   /* Store these things on disk used to derive key later: */
        int iterationCount = 1000;
        int saltLength = 32; // bytes; should be the same size
//        as the output (256 / 8 = 32)
        int keyLength = 256; // 256-bits for AES-256, 128-bits for AES-128, etc
//        byte[] salt; // Should be of saltLength

   /* When first creating the key, obtain a salt with this: */
        SecureRandom random = new SecureRandom();
        byte[] salt = new byte[saltLength];
        random.nextBytes(salt);

   /* Use this to derive the key from the password: */
        KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt,
                iterationCount, keyLength);
        SecretKeyFactory keyFactory = null;
        try {
            keyFactory = SecretKeyFactory
                    .getInstance("PBKDF2WithHmacSHA1");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        byte[] keyBytes = new byte[0];
        try {
            keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
        SecretKey key = new SecretKeySpec(keyBytes, "AES");

    }
}
